<?php


namespace app\miniapp\controller;


use app\common\controller\Api;
use app\miniapp\model\AddressModel;
use app\miniapp\validate\AddressValidate;

class Address extends Base
{
    protected $noNeedLogin = '*';
    //收货地址列表
    public function list()
    {
        $list = AddressModel::where('user_id', $this->userId)
            ->order('id','DESC')
            ->field('id,name,mobile,area,address')
            ->select();
//        if (!$list) {
//            $this->error('查询失败');
//        }
        $this->success('查询成功',[
            'list' => $list
        ]);
    }
    public function list2()
    {
        $page = input('page/d',1);
        $list = AddressModel::where('user_id', $this->userId)
            ->order('id','DESC')
            ->page($page,10)
            ->field('id,name,mobile,area,address')
            ->select();
        $count = AddressModel::where('user_id', $this->userId)
            ->count();
        $this->success('查询成功',[
            'total_page' => ceil($count / 10),
            'list' => $list
        ]);
    }
    //新增收货地址
    public function add()
    {
        $data = input('post.');
        $validate = new AddressValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        $data['user_id'] = $this->userId;
        $data['create_time'] = date('Y-m-d H:i:s');
        $add = AddressModel::create($data);
        if (!$add) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    //查询修改地址
    public function editList()
    {
        $id = input('id/d');
        if (empty($id)) {
            $this->error('id不能为空');
        }
        $list = AddressModel::field('id,name,mobile,area,address')
            ->find($id);
        if (!$list) {
            $this->error('查询失败');
        }
        $this->success('查询成功',[
            'list' => $list
        ]);

    }
    //修改地址
    public function edit()
    {
        $data = input('post.');
        $validate = new AddressValidate();
        $res = $validate->scene('edit')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        $edit = AddressModel::find($data['id']);
        if (!$edit) {
            $this->error('未有该数据');
        }
        $edit->name = $data['name'];
        $edit->mobile = $data['mobile'];
        $edit->area = $data['area'];
        $edit->address = $data['address'];
        if ($edit->save()) {
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }
    //删除收货地址
    public function del()
    {
        $id = input('id/d');
        if (empty($id)) {
            $this->error('id不能为空');
        }
        $del = AddressModel::find($id);
        if (!$del) {
            $this->error('没有该数据');
        }
        if ($del->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

}